package com.yinp.proapp.utils;

import android.Manifest;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.view.LayoutInflater;

import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewbinding.ViewBinding;

import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.yinp.proapp.R;
import com.yinp.proapp.constant.Constant;
import com.yinp.proapp.databinding.DialogSelectTakePhotoBinding;
import com.yinp.proapp.view.PermissionDialog;
import com.yinp.tools.fragment_dialog.BaseDialogFragment;
import com.yinp.tools.fragment_dialog.CommonDialogFragment;
import com.yinp.tools.fragment_dialog.DialogFragmentHolder;
import com.yinp.tools.fragment_dialog.ViewConvertListener;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @author :yinpeng
 * date      :2021/8/18
 * package   :com.yinp.proapp.utils
 * describe  :
 */
public class SelectTakePhoto {
    public Uri imageUri;
    public int type;

    public void selectType(FragmentActivity activity, int requestCode) {
        CommonDialogFragment.newInstance().setLayout(DialogSelectTakePhotoBinding.inflate(LayoutInflater.from(activity), null, false))
                .setViewConvertListener(new ViewConvertListener() {
                    @Override
                    public void convertView(DialogFragmentHolder holder, BaseDialogFragment dialogFragment, ViewBinding viewBinding) {
                        DialogSelectTakePhotoBinding binding = (DialogSelectTakePhotoBinding) viewBinding;
                        binding.tvTakePhoto.setOnClickListener(v -> {
                            getPermission(activity, type = Constant.TAKE_PHOTO, requestCode, dialogFragment);
                        });
                        binding.tvPicture.setOnClickListener(v -> {
                            getPermission(activity, type = Constant.SELECT_PHOTO, requestCode, dialogFragment);
                        });
                        binding.tvCancel.setOnClickListener(v -> {
                            dialogFragment.dismiss();
                        });
                    }
                }).setAnimStyle(R.style.BottomDialogAnimation).setGravity(BaseDialogFragment.BOTTOM).setPercent(true, false)
                .show(activity.getSupportFragmentManager());
    }

    public void selectType(Fragment fragment, int requestCode) {
        CommonDialogFragment.newInstance().setLayout(DialogSelectTakePhotoBinding.inflate(LayoutInflater.from(fragment.getContext()), null, false))
                .setViewConvertListener(new ViewConvertListener() {
                    @Override
                    public void convertView(DialogFragmentHolder holder, BaseDialogFragment dialogFragment, ViewBinding viewBinding) {
                        DialogSelectTakePhotoBinding binding = (DialogSelectTakePhotoBinding) viewBinding;
                        binding.tvTakePhoto.setOnClickListener(v -> {
                            getPermission(fragment, type = Constant.TAKE_PHOTO, requestCode, dialogFragment);
                        });
                        binding.tvPicture.setOnClickListener(v -> {
                            getPermission(fragment, type = Constant.SELECT_PHOTO, requestCode, dialogFragment);
                        });
                        binding.tvCancel.setOnClickListener(v -> {
                            dialogFragment.dismiss();
                        });
                    }
                }).setAnimStyle(R.style.BottomDialogAnimation).setGravity(BaseDialogFragment.BOTTOM).setPercentSize(0f, 0f).show(fragment.getChildFragmentManager());
    }

    private void getPermission(Fragment fragment, int type, int requestCode, BaseDialogFragment dialogFragment) {
        String[] permission;
        if (type == Constant.TAKE_PHOTO) {
            permission = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        } else if (type == Constant.SELECT_PHOTO){
            permission = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
        }else {
            return;
        }
        XXPermissions.with(fragment.getContext())
                .permission(permission)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                            switch (type) {
                                case Constant.TAKE_PHOTO:
                                    takePhoto(fragment, requestCode, dialogFragment);
                                    break;
                                case Constant.SELECT_PHOTO:
                                    SelectPhoto(fragment, requestCode, dialogFragment);
                                    break;
                            }
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            PermissionDialog permissionDialog = new PermissionDialog(fragment.getActivity(), fragment.getString(R.string.per_tips, fragment.getString(R.string.storage)), permissions);
                            permissionDialog.show();
                        }
                    }
                });
    }

    private void getPermission(Activity activity, int type, int requestCode, BaseDialogFragment dialogFragment) {
        String[] permission;
        if (type == Constant.TAKE_PHOTO) {
            permission = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        } else if (type == Constant.SELECT_PHOTO){
            permission = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
        }else {
            return;
        }
        XXPermissions.with(activity)
                .permission(permission)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                            switch (type) {
                                case Constant.TAKE_PHOTO:
                                    takePhoto(activity, requestCode, dialogFragment);
                                    break;
                                case Constant.SELECT_PHOTO:
                                    SelectPhoto(activity, requestCode, dialogFragment);
                                    break;
                            }
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            PermissionDialog permissionDialog = new PermissionDialog(activity, activity.getString(R.string.per_tips, activity.getString(R.string.storage)), permissions);
                            permissionDialog.show();
                        }
                    }
                });
    }

    private void takePhoto(Fragment fragment, int requestCode, BaseDialogFragment dialogFragment) {
        imageUri = null;
        File file = new File(fragment.getContext().getExternalCacheDir(), "output_image.jpg");
        try {
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (Build.VERSION.SDK_INT >= 24) {
            imageUri = FileProvider.getUriForFile(fragment.getContext(), "com.yinp.proapp", file);
        } else {
            imageUri = Uri.fromFile(file);
        }
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        fragment.startActivityForResult(intent, requestCode);
        dialogFragment.dismiss();
    }

    private void takePhoto(Activity activity, int requestCode, BaseDialogFragment dialogFragment) {
        imageUri = null;
        File file = new File(activity.getExternalCacheDir(), "output_image.jpg");
        try {
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (Build.VERSION.SDK_INT >= 24) {
            imageUri = FileProvider.getUriForFile(activity, "com.yinp.proapp", file);
        } else {
            imageUri = Uri.fromFile(file);
        }
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        activity.startActivityForResult(intent, requestCode);
        dialogFragment.dismiss();
    }

    private void SelectPhoto(Fragment fragment, int requestCode, BaseDialogFragment dialogFragment) {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        fragment.startActivityForResult(intent, requestCode);
        dialogFragment.dismiss();
    }

    private void SelectPhoto(Activity activity, int requestCode, BaseDialogFragment dialogFragment) {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        activity.startActivityForResult(intent, requestCode);
        dialogFragment.dismiss();
    }

    public String handleImageOnKitKat(Context context, Intent data) {
        String imagePath = null;
        Uri pictureUri = data.getData();
        if (DocumentsContract.isDocumentUri(context, pictureUri)) {
            String docId = DocumentsContract.getDocumentId(pictureUri);
            if ("com.android.providers.media.documents".equals(pictureUri.getAuthority())) {
                String id = docId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection, context);
            } else if ("com.android.providers.downloads.documents".equals(pictureUri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null, context);
            }
        } else if ("content".equalsIgnoreCase(pictureUri.getScheme())) {
            //如果是content类型的uri，则使用普通类型
            imagePath = getImagePath(pictureUri, null, context);
        } else if ("file".equalsIgnoreCase(pictureUri.getScheme())) {
            //如果是file类型的uri，则直接获取图片的路径即可
            imagePath = pictureUri.getPath();
        }
        return imagePath;
    }

    private String getImagePath(Uri uri, String selection, Context context) {
        String path = null;
        //通过uri和selection来获取图片的真实路径
        Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.Media.DATA
        }, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }
}
